var express = require('express');
var router = express.Router();
const conn = require('./db/conn');
const { verify } = require('../utils/index')
const path = require('path'); //引入path模块
const { formidable } = require('formidable'); //使用formidable库上传图片
const fs = require('fs');
//引入随机id
const { generateUserId } = require('../utils/index')
// 查询店铺信息
router.get('/info', (req, res) => {
    let { shopid } = req.query
    let r = verify({ shopid })
    if (!r.flag) {
        res.send({ code: 5001, success: false, msg: '参数错误' })
        console.log(r.arr);
        return
    }
    let sql = `select * from shopname where shopid='${shopid}'`
    conn.query(sql, (error, results) => {
        if (error) throw error;
        if (results.length > 0) {
            res.send({ code: 0, success: true, msg: '获取数据成功', data: results[0] })

        } else {
            res.send({ code: 3, success: false, msg: '您没有权限查看数据' })
        }
    })
});

//存储店铺的员工账号
router.post('/staffadd', (req, res) => {

    let { sid, acc, pwd, region, name } = req.body
    let r = verify({ sid, acc, pwd, region, name })
    if (!r.flag) {
        res.send({ code: 5001, success: false, msg: '参数错误' })
        console.log(r.arr);
        return
    }
    let sql = `select * from student where acc='${acc}'and sid=${sid}`
    conn.query(sql, (error, results) => {
        if (error) throw error;
        if (results.length > 0) {
            return res.send({ code: 3, success: false, msg: '账号重复了,请重新输入' })
        }
        let sql = `insert into student(name,password,region,tel,acc,sid,mid) values('${name}','${pwd}','${region}','${acc}','${acc}','${sid}','${generateUserId()}')`
        conn.query(sql, (error, results) => {
            if (error) throw error;
            if (results.affectedRows > 0) {
                res.send({ code: 0, success: true, msg: '添加成功' })
            } else {
                res.send({ code: 1, success: false, msg: '添加失败' })
            }
        })
    })
});

//查询店铺的账号列表
router.post('/querystaff', (req, res) => {
    let { shopid } = req.body
    let r = verify({ shopid })
    if (!r.flag) {
        res.send({ code: 5001, success: false, msg: '参数错误' })
        console.log(r.arr);
        return
    }
    let sql = `select * from student where sid='${shopid}'`
    conn.query(sql, (error, results) => {
        if (error) throw error;
        if (results.length > 0) {
            res.send({ code: 0, success: true, msg: '获取数据成功', data: results })
        }
    })
});

//修改员工的账号和密码
router.post('/updatestaff', (req, res) => {
    let { acc, pwd, mid } = req.body
    let setClauses = [];
    if (pwd !== undefined) setClauses.push(`password='${pwd}'`);
    if (acc !== undefined) setClauses.push(`tel='${acc}'`);
    if (setClauses.length === 0) {
        res.send({ code: 5002, success: false, msg: '没有要修改的数据' });
        return;
    }
    const setClause = setClauses.join(',');
    console.log(`${setClause}`);
    const sql = `UPDATE student SET ${setClause} WHERE  mid='${mid}'`;
    conn.query(sql, (error, results) => {
        if (error) throw error;
        if (results.affectedRows > 0) {
            res.send({ code: 0, success: true, msg: '修改成功' })
        }
    })
})

//删除员工账号
router.post('/deletestaff', (req, res) => {
    let { mid } = req.body
    let r = verify({ mid })
    if (!r.flag) {
        res.send({ code: 5001, success: false, msg: '参数错误' })
        console.log(r.arr);
        return
    }
    let sql = `delete from student where mid='${mid}'`
    conn.query(sql, (error, results) => {
        if (error) throw error;
        if (results.affectedRows > 0) {
            res.send({ code: 0, success: true, msg: '删除成功' })
        }
    })
})

//上传店铺图片]
router.post('/uploadimg', (req, res) => {

    const form = formidable({
        uploadDir: path.resolve(__dirname, '../public/images'),//设置上传文件保存的路径
        keepExtensions: true,//保持上传文件的扩展名
    });
    form.parse(req, (err, fields, { file }) => {
        if (err) {
            next(err);
            return;
        }
        let sid = fields.id[0];
        let setUrl = `s_imgurl='${file[0].newFilename}'`;

        // 查询已有的图片
        const querySql = `select * from shopname where shopid='${sid}'`
        conn.query(querySql, (error, results) => {
            if (error) throw error
            if (results.length > 0) {
                let imgUrl = results[0].s_imgurl;
                if (imgUrl) {
                    const imagesPath = path.resolve(__dirname, `../public/images/${imgUrl}`);
                    // 或者使用同步删除
                    try {
                        fs.rmSync(imagesPath, { recursive: true });
                        console.log('图片已成功删除');
                    } catch (err) {
                        console.error(`发生错误：${err}`);
                    }
                }

            }
        })
        const sql = `UPDATE shopname SET ${setUrl} WHERE shopid='${sid}'`;
        conn.query(sql, (error, results) => {
            if (error) throw error
            if (results.affectedRows > 0) {
                res.send({ code: 0, success: true, msg: '上传成功', file })
            }
        })
    })
})



module.exports = router;